package com.lhkj.ct.admin.system.controller;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.lhkj.ct.base.constants.CacheConstants;
import com.lhkj.ct.base.model.ro.ActionResult;
import com.lhkj.ct.meta.admin.model.vo.SysCache;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * 缓存监控
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("api/system/cache")
@Api(tags = "16.缓存管理")
@ApiSupport(order = 16)
@Validated
public class SysCacheController {
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    private final static List<SysCache> caches = new ArrayList<SysCache>();

    {
        caches.add(new SysCache(CacheConstants.LOGIN_TOKEN_KEY, "用户信息"));
        caches.add(new SysCache(CacheConstants.SYS_CONFIG_KEY, "配置信息"));
        caches.add(new SysCache(CacheConstants.SYS_DICT_OPTION_KEY, "数据字典"));
        caches.add(new SysCache(CacheConstants.CAPTCHA_CODE_KEY, "验证码"));
        caches.add(new SysCache(CacheConstants.REPEAT_SUBMIT_KEY, "防重提交"));
        caches.add(new SysCache(CacheConstants.RATE_LIMIT_KEY, "限流处理"));
        caches.add(new SysCache(CacheConstants.PWD_ERR_CNT_KEY, "密码错误次数"));
    }

    @ApiOperation(value = "缓存监控")
    @GetMapping()
    public ActionResult<Map<String, Object>> getInfo() throws Exception {
        Properties info = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info());
        Properties commandStats = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info("commandstats"));
        Object dbSize = redisTemplate.execute((RedisCallback<Object>) connection -> connection.dbSize());

        Map<String, Object> result = new HashMap<>(3);
        result.put("info", info);
        result.put("dbSize", dbSize);

        List<Map<String, String>> pieList = new ArrayList<>();
        commandStats.stringPropertyNames().forEach(key -> {
            Map<String, String> data = new HashMap<>(2);
            String property = commandStats.getProperty(key);
            data.put("name", StringUtils.removeStart(key, "cmdstat_"));
            data.put("value", StringUtils.substringBetween(property, "calls=", ",usec"));
            pieList.add(data);
        });
        result.put("commandStats", pieList);
        return ActionResult.success(result);
    }

    @ApiOperation(value = "缓存列表")
    @GetMapping("/getNames")
    public ActionResult<List<SysCache>> cache() {
        return ActionResult.success(caches);
    }

    @ApiOperation(value = "键名列表")
    @GetMapping("/getKeys/{cacheName}")
    public ActionResult<Set<String>> getCacheKeys(@PathVariable String cacheName) {
        Set<String> cacheKeys = redisTemplate.keys(cacheName + "*");
        return ActionResult.success(cacheKeys);
    }
    @ApiOperation(value = "缓存内容")
    @GetMapping("/getValue/{cacheName}/{cacheKey}")
    public ActionResult<SysCache> getCacheValue(@PathVariable String cacheName, @PathVariable String cacheKey) throws JsonProcessingException {
        String redisKey = cacheName + ":" + cacheKey;
        Object value = redisTemplate.opsForValue().get(redisKey);
        SysCache sysCache = new SysCache(cacheName, cacheKey, new ObjectMapper().writeValueAsString(value));
        return ActionResult.success(sysCache);
    }

    @ApiOperation(value = "删除缓存列表")
    @DeleteMapping("/clearCacheName/{cacheName}")
    public ActionResult<Void> clearCacheName(@PathVariable String cacheName) {
        Collection<String> cacheKeys = redisTemplate.keys(cacheName + "*");
        redisTemplate.delete(cacheKeys);
        return ActionResult.success();
    }

    @ApiOperation(value = "删除缓存键")
    @DeleteMapping("/clearCacheKey/{cacheKey}")
    public ActionResult<Void> clearCacheKey(@PathVariable String cacheKey) {
        redisTemplate.delete(cacheKey);
        return ActionResult.success();
    }

//    @DeleteMapping("/clearCacheAll")
//    public ActionResult clearCacheAll() {
//        Collection<String> cacheKeys = redisTemplate.keys("*");
//        redisTemplate.delete(cacheKeys);
//        return ActionResult.success();
//    }
}
